<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>业务管理 - 创建业务</title>
    <link rel="stylesheet" href="../../css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script type="module" src="../../js/components/navigation.js"></script>
    <script type="module" src="../../js/utils.js"></script>
    <script type="module" src="../../js/api.js"></script>
</head>
<body>
    <div class="loading-overlay" id="loading-overlay">
        <div class="loading-spinner"></div>
    </div>

    <div class="toast" id="toast"></div>

    <div class="app-container">
        <header class="app-header">
            <div class="logo">
                <i class="fas fa-building"></i> 员工管理系统
            </div>
            <div class="user-info">
                <span id="username-display" class="username"></span>
                <button id="logout-btn" class="btn btn-secondary">
                    <i class="fas fa-sign-out-alt"></i> 退出登录
                </button>
            </div>
        </header>

        <div class="app-body">
            <aside class="sidebar">
                <nav class="menu">
                    <ul>
                        <li><a href="#" class="menu-item active" data-target="welcome">欢迎页</a></li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">员工管理</a>
                            <ul class="submenu">
                                <li><a href="../employee/list.html" class="submenu-item">员工列表</a></li>
                                <li><a href="../employee/add.html" class="submenu-item">添加员工</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">业务管理</a>
                            <ul class="submenu">
                                <li><a href="../business/list.html" class="submenu-item">业务列表</a></li>
                                <li><a href="../business/create.html" class="submenu-item">创建业务</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">薪酬管理</a>
                            <ul class="submenu">
                                <li><a href="../salary/overview.html" class="submenu-item">薪酬概览</a></li>
                                <li><a href="../salary/manage.html" class="submenu-item">薪酬管理</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">系统设置</a>
                            <ul class="submenu">
                                <li><a href="../system/user.html" class="submenu-item">用户管理</a></li>
                                <li><a href="../system/profile.html" class="submenu-item">个人设置</a></li>
                            </ul>
                        </li>
                    </ul>
                </nav>
            </aside>

            <main class="content">
                <div class="page-header">
                    <h1><i class="fas fa-project-diagram"></i> 创建业务</h1>
                    <div class="breadcrumb">
                        <a href="#"><i class="fas fa-home"></i> 首页</a> &gt;
                        <a href="list.html"><i class="fas fa-project-diagram"></i> 业务管理</a> &gt;
                        <span><i class="fas fa-plus-circle"></i> 创建业务</span>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h2>业务信息表单</h2>
                    </div>
                    <div class="card-body">
                        <form id="create-business-form" class="form-horizontal">
                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <label for="name" class="form-label">业务名称 <span class="required">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text"><i class="fas fa-tag"></i></span>
                                        </div>
                                        <input type="text" id="name" name="name" class="form-control" placeholder="请输入业务名称">
                                    </div>
                                    <div class="form-error" id="name-error"></div>
                                </div>

                                <div class="form-group col-md-6">
                                    <label for="status" class="form-label">状态 <span class="required">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text"><i class="fas fa-clipboard-check"></i></span>
                                        </div>
                                        <select id="status" name="status" class="form-control">
                                            <option value="">请选择状态</option>
                                            <option value="未开始">未开始</option>
                                            <option value="进行中">进行中</option>
                                            <option value="已完成">已完成</option>
                                            <option value="已暂停">已暂停</option>
                                        </select>
                                    </div>
                                    <div class="form-error" id="status-error"></div>
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <label for="startDate" class="form-label">开始日期 <span class="required">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text"><i class="fas fa-calendar-alt"></i></span>
                                        </div>
                                        <input type="date" id="startDate" name="startDate" class="form-control">
                                    </div>
                                    <div class="form-error" id="startDate-error"></div>
                                </div>

                                <div class="form-group col-md-6">
                                    <label for="endDate" class="form-label">结束日期 <span class="required">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text"><i class="fas fa-calendar-check"></i></span>
                                        </div>
                                        <input type="date" id="endDate" name="endDate" class="form-control">
                                    </div>
                                    <div class="form-error" id="endDate-error"></div>
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <label for="revenue" class="form-label">预计收入 <span class="required">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text"><i class="fas fa-money-bill-wave"></i></span>
                                        </div>
                                        <input type="number" id="revenue" name="revenue" class="form-control" placeholder="请输入预计收入" step="0.01">
                                    </div>
                                    <div class="form-error" id="revenue-error"></div>
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-group col-md-12">
                                    <label for="description" class="form-label">业务描述</label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text"><i class="fas fa-align-left"></i></span>
                                        </div>
                                        <textarea id="description" name="description" class="form-control" rows="4" placeholder="请输入业务描述"></textarea>
                                    </div>
                                    <div class="form-error" id="description-error"></div>
                                </div>
                            </div>

                            <div class="action-buttons">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> 提交
                                </button>
                                <a href="list.html" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> 取消
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script>
        import { api } from '../../js/api.js';
        <!-- 移除ES6模块导入，使用全局对象 -->
        import { initNavigation } from '../../js/components/navigation.js';

        document.addEventListener('DOMContentLoaded', function() {
            // 初始化导航
            initNavigation('main-menu', '业务管理', '创建业务');

            // 检查登录状态
            checkLoginStatus();

            // 显示用户名
            const username = localStorage.getItem('username');
            if (username) {
                document.getElementById('username-display').textContent = username;
            }

            // 退出登录
            document.getElementById('logout-btn').addEventListener('click', function() {
                localStorage.removeItem('token');
                localStorage.removeItem('username');
                window.location.href = '../../index.html';
            });

            // 表单提交事件
            document.getElementById('create-business-form').addEventListener('submit', function(e) {
                e.preventDefault();

                // 表单验证
                if (!validateForm()) {
                    return;
                }

                // 显示加载状态
                showLoading(true);

                // 获取表单数据
                const formData = {
                    name: document.getElementById('name').value.trim(),
                    description: document.getElementById('description').value.trim(),
                    startDate: document.getElementById('startDate').value.trim(),
                    endDate: document.getElementById('endDate').value.trim(),
                    status: document.getElementById('status').value.trim(),
                    revenue: parseFloat(document.getElementById('revenue').value.trim())
                };

                // 提交表单数据
                api.business.create(formData)
                    .then(response => {
                        showLoading(false);
                        if (response) {
                            showToast('创建成功', 'success');
                            setTimeout(() => {
                                window.location.href = 'list.html';
                            }, 1500);
                        } else {
                            showToast('创建失败', 'error');
                        }
                    })
                    .catch(error => {
                        showLoading(false);
                        console.error('Failed to create business:', error);
                        showToast('创建失败，请重试', 'error');
                    });
            });

            // 实时表单验证
            const formInputs = document.querySelectorAll('#create-business-form input, #create-business-form select, #create-business-form textarea');
            formInputs.forEach(input => {
                input.addEventListener('blur', function() {
                    validateField(this);
                });
            });

            function checkLoginStatus() {
                const token = localStorage.getItem('token');
                if (!token) {
                    window.location.href = '../../index.html';
                }
            }

            function validateForm() {
                let isValid = true;

                // 验证所有字段
                formInputs.forEach(input => {
                    if (!validateField(input)) {
                        isValid = false;
                    }
                });

                return isValid;
            }

            function validateField(input) {
                const id = input.id;
                const value = input.value.trim();
                let errorMessage = '';

                switch(id) {
                    case 'name':
                        if (!value) {
                            errorMessage = '请输入业务名称';
                        }
                        break;
                    case 'startDate':
                        if (!value || !Validator.isDate(value)) {
                            errorMessage = '请选择有效的开始日期';
                        } else if (document.getElementById('endDate').value && new Date(value) > new Date(document.getElementById('endDate').value)) {
                            errorMessage = '开始日期不能晚于结束日期';
                        }
                        break;
                    case 'endDate':
                        if (!value || !Validator.isDate(value)) {
                            errorMessage = '请选择有效的结束日期';
                        } else if (document.getElementById('startDate').value && new Date(document.getElementById('startDate').value) > new Date(value)) {
                            errorMessage = '结束日期不能早于开始日期';
                        }
                        break;
                    case 'status':
                        if (!value) {
                            errorMessage = '请选择状态';
                        }
                        break;
                    case 'revenue':
                        if (!value || !Validator.isMoney(value) || value <= 0) {
                            errorMessage = '请输入有效的预计收入';
                        }
                        break;
                }

                const errorElement = document.getElementById(`${id}-error`);
                if (errorMessage) {
                    errorElement.textContent = errorMessage;
                    errorElement.style.display = 'block';
                    input.classList.add('invalid');
                    return false;
                } else {
                    errorElement.style.display = 'none';
                    input.classList.remove('invalid');
                    return true;
                }
            }

            function showToast(message, type) {
                const toast = document.getElementById('toast');
                toast.textContent = message;
                toast.className = 'toast show ' + type;

                setTimeout(() => {
                    toast.className = 'toast';
                }, 3000);
            }

            function showLoading(show) {
                const loadingOverlay = document.getElementById('loading-overlay');
                loadingOverlay.style.display = show ? 'flex' : 'none';
            }
        });
    </script>
</body>
</html>